package com.fangs.lunbotu.banner;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;

import com.fangs.lunbotu.Apps;


public class MyBannerVideoView extends TextureVideoView {

    private String url;
    private boolean loop;//是否循环播放
    private ShowLoadingListener showLoadingListener;
    private final Handler mVideoViewHandler = new Handler();
    private final Runnable runable_play = new Runnable() {
        @Override
        public void run() {
            if (getCurrentPosition() > 50) { // 避免虽然开始播放但画面未显示仍黑屏情况 故延迟50毫秒消除蒙版
                if (scaleError) {
                    setScale();
                    scaleError = false;
                }

                showLoadingListener.showLoading(false);
                mVideoViewHandler.removeCallbacks(runable_play);
            } else {
                mVideoViewHandler.postDelayed(runable_play, 100);
            }
        }
    };
    private float mScaleX;
    private boolean scaleError;

    public MyBannerVideoView(Context context, boolean loop) {
        this(context);
        this.loop = loop;
        init();
    }

    private MyBannerVideoView(Context context) {
        super(context);
    }

    private void init() {
        setOnPreparedListener(mp -> {
            float videoRatio = mp.getVideoWidth() / (float) mp.getVideoHeight();
            float screenRatio = getWidth() / (float) getHeight();
            mScaleX = videoRatio / screenRatio;
            setScale();
            mp.setVolume(0, 0);
        });
        setOnCompletionListener(mp -> {
            if (loop) {
                mp.start();
                mp.setLooping(true);
            }
        });
        setOnInfoListener((mp, what, extra) -> {
            switch (what) {
                case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                    showLoadingListener.showBuffering(true);
                    break;
                case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                    showLoadingListener.showBuffering(false);
                    break;
            }
            return true;
        });
        setOnErrorListener((mp, what, extra) -> {
            showLoading();
            setUrl(url); //播放报错时（有可能是视频缓存被清理）重置播放路径 以便app不退出视频也可重新缓存
            return true;
        });
    }

    public void setScale() {
        // setScale 为处理视频尺寸不符合banner时 拉伸变形问题
        if (mScaleX >= 1f) {
            setScaleX(mScaleX);
        } else {
            setScaleY(1f / mScaleX);
        }
    }

    public void setScaleError() { // 处理侧滑退出 回到banner页 视频控件内容突然显示不全问题
        if (mScaleX >= 1f) {
            setScaleX(1);
        } else {
            setScaleY(1);
        }
        scaleError = true;
    }

    public void setUrl(String url) {
        try {
            String proxyUrl = Apps.getProxy().getProxyUrl(url);
            setVideoURI(Uri.parse(proxyUrl));
            if (!Apps.getProxy().isCached(url)) {
                Apps.preCacherScreenData(proxyUrl);//开始预加载缓存视频
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        this.url = url;
    }

    public void setShowLoadingListener(ShowLoadingListener showLoadingListener) {
        this.showLoadingListener = showLoadingListener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = getDefaultSize(getWidth(), widthMeasureSpec);
        int height = getDefaultSize(getHeight(), heightMeasureSpec);
        setMeasuredDimension(width, height);
    }

    @Override
    public void start() {
        super.start();
        if (showLoadingListener != null) {
            if (getCurrentPosition() < 50) {
                showLoading();
            } else {
                mVideoViewHandler.postDelayed(runable_play, 100);
            }
        }
    }

    private void showLoading() {
        showLoadingListener.showLoading(true);
        mVideoViewHandler.postDelayed(runable_play, 100); //处理 播放前短暂黑屏情况 和 封面到过渡闪屏问题
    }

    public interface ShowLoadingListener {
        void showLoading(boolean show);

        void showBuffering(boolean show);
    }
}
